import json
from apis import api_routes
from flask import g, request, jsonify
from security.decoration import certification
from models.logs.logs import Logs
from typing import Union
from models.facility.facility import Facility
from sqlalchemy import and_
from typing import List
from models.course.detailed import Detailed


@api_routes.route("/report/machine", methods=["GET"])
# @certification(auth=True, role=None)
def func_report_machine_get_api():
    """
    报表查询设备实时状态，完成API开发
    http://127.0.0.1:8080/api/report/machine
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    {
    }
    :return:
        {'status': 200, 'data': resp, "index": index, "size": size, "total": count, "pages": page}
    ---
    tags:
      - 看板数据接口
    """
    resp: list = []
    parm: Union[str, None] = None

    data: List[Facility] = g.session.query(Facility).filter(Facility.uuid4 != parm).order_by(Facility.id).all()
    for index, itr in enumerate(data):

        uuid4key: bool = True if itr.uuid4 is not None else False
        status: Union[str, None] = "PLC未对接"
        if uuid4key is True:
            uuid4value = g.cache.get(str(itr.uuid4))

            if uuid4value is not None:
                status = uuid4value
            else:
                status = "连接PLC超时"

        resp.append({
            "serials": itr.serials,
            "name": itr.name,
            "status": status,
            "connect": False if (status == "连接PLC超时" or status == "设备未对接PLC") else True
        })
    return jsonify({'status': 200, 'data': resp})
